package com.xxxy.dongyexuan.action;

import com.xxxy.dongyexuan.mapper.IFlowMapper;
import com.xxxy.dongyexuan.mapper.IOrderMapper;
import com.xxxy.dongyexuan.mapper.IReservationMapper;
import com.xxxy.dongyexuan.mapper.IUserMapper;
import com.xxxy.dongyexuan.po.*;
import com.xxxy.dongyexuan.service.impl.PayService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.Date;
import java.util.List;
import java.util.UUID;

@RestController
@CrossOrigin
public class ReservationAction {

    @Autowired
    private IReservationMapper mapper;

    @Autowired
    private IOrderMapper orderMapper;

    @Autowired
    private PayService payService;

    @Autowired
    private IUserMapper userMapper;


    //分页查询
    @GetMapping("/reservation/{pagenow}/{pagesize}")
    public PageBean findByPage(@PathVariable("pagenow") int pagenow, @PathVariable("pagesize") int pagesize){
        int from =(pagenow-1)*pagesize;//开始条数
        int total = this.mapper.getcount();//总条数
        int pages =(total-1)/pagesize+1;//计算总页数
        List data = this.mapper.findByPage(from,pagesize);
        PageBean pageBean = new PageBean();
        pageBean.setPages(pages);
        pageBean.setPagenow(pagenow);
        pageBean.setPagesize(pagesize);
        pageBean.setTotal(total);
        pageBean.setData(data);
        return pageBean;
    }

    @GetMapping("/reservationFindLog/{pagenow}/{pagesize}")
    public PageBean findLogByPage(@PathVariable("pagenow") int pagenow,
                                  @PathVariable("pagesize") int pagesize,
                                  @RequestParam("uid") int uid ){
        int from =(pagenow-1)*pagesize;//开始条数
        int total = this.mapper.getcount();//总条数
        int pages =(total-1)/pagesize+1;//计算总页数
        List data = null;
        if (uid > 0) {
            data = this.mapper.findLogByPage(from, pagesize, uid);
        } else {
            data = this.mapper.findAllLogByPage(from, pagesize);
        }
        PageBean pageBean = new PageBean();
        pageBean.setPages(pages);
        pageBean.setPagenow(pagenow);
        pageBean.setPagesize(pagesize);
        pageBean.setTotal(total);
        pageBean.setData(data);
        return pageBean;
    }



    //查询所有
    @GetMapping("/reservation")
    public List<Reservation> findAll(){
        List<Reservation> list = this.mapper.findAll();
        return list;
    }

    //根据员工号查询
    @GetMapping("/reservation/{rid}")
    public Reservation findById(@PathVariable("rid") int rid){
        Reservation reservation = this.mapper.findById(rid);
        return reservation;
    }

    @GetMapping("/reservationLog/{rid}/{menuname}")
    public List<Reservation> findLogById(@PathVariable("rid") int rid,@PathVariable("menuname") String menuname){
        System.out.println("menuname"+menuname);
        List<Reservation> reservation = this.mapper.findLogById(rid,menuname);
        return reservation;
    }

    //增加
    @PostMapping("/reservation")
    public int save(Reservation reservation){
        int result = this.mapper.save(reservation);
        return result;
    }

    @PostMapping("/reservationLog")
    public String reservationLog(Reservation reservation){

        // 需要先判断当前用户的余额，不够抛出错误
        User user = userMapper.findById(reservation.getUid());
        reservation.setRtime(new Date());
        if (reservation.getWay() == 2) {
            if (user.getMoney() < reservation.getMoney()) {
                return "failure";
            }

            // 余额支付
            // 直接扣减余额
            userMapper.updateMoney(-reservation.getMoney().intValue(), reservation.getUid());
            reservation.setState(1);
            String orderId = UUID.randomUUID().toString().replace("-", "").toUpperCase();
            reservation.setOrderId(orderId);
            this.mapper.saveLog(reservation);

            // 返回支付参数并显示
            Order order = new Order();
            order.setOrderId(orderId);
            order.setPaymentType(reservation.getWay());
            order.setTransType(1);
            order.setTotalAmt(reservation.getMoney().intValue());
            order.setRid(reservation.getRid());
            order.setCreateTime(LocalDateTime.now());
            order.setUpdateTime(LocalDateTime.now());
            order.setUid(reservation.getUid());
            order.setPayStatus(1);
            // 进行订单生成
            order.setPaySuccessTime(LocalDateTime.now());
            order.setCreateTime(LocalDateTime.now());
            order.setUpdateTime(LocalDateTime.now());
            order.setRealAmt(order.getTotalAmt());
            orderMapper.save(order);
        } else {
            String orderId = UUID.randomUUID().toString().replace("-", "").toUpperCase();
            reservation.setOrderId(orderId);
            this.mapper.saveLog(reservation);
            // 返回支付参数并显示
            Order order = new Order();
            order.setOrderId(orderId);
            order.setPaymentType(reservation.getWay());
            order.setTransType(1);
            order.setTotalAmt(reservation.getMoney().intValue());
            order.setRid(reservation.getRid());
            order.setUid(reservation.getUid());
            order.setCreateTime(LocalDateTime.now());
            order.setUpdateTime(LocalDateTime.now());
            return payService.unifiedOrder(order);
        }


        return "success";
    }

    //修改
    @PutMapping("/reservation")
    public int update(Reservation reservation){
        int result = this.mapper.merge(reservation);
        return result;
    }

    //删除
    @DeleteMapping("/reservation/{rid}")
    public int delete(@PathVariable("rid") int rid){
        int result = this.mapper.delete(rid);
        return result;
    }

    @DeleteMapping("/reservationDelLog/{rid}")
    public int deleteLog(@PathVariable("rid") int rid) {

        // 用户余额进行增加余额，同步扣除预约费用的50%
        Reservation reservation = this.mapper.findById(rid);
        User user = userMapper.findById(reservation.getUid());
        int result = this.mapper.deleteLog(rid);
        if (user.getRole() == 1) {
            userMapper.updateMoney((int) (reservation.getMoney() * 0.5), reservation.getUid());
            // 返回支付参数并显示
            Order order = new Order();
            order.setOrderId(UUID.randomUUID().toString().replace("-", "").toUpperCase());
            order.setPaymentType(reservation.getWay());
            order.setTransType(2);
            order.setTotalAmt((int) (reservation.getMoney() * 0.5));
            order.setRid(reservation.getRid());
            order.setCreateTime(LocalDateTime.now());
            order.setUpdateTime(LocalDateTime.now());
            order.setUid(reservation.getUid());
            order.setPayStatus(1);
            // 进行订单生成
            order.setPaySuccessTime(LocalDateTime.now());
            order.setCreateTime(LocalDateTime.now());
            order.setUpdateTime(LocalDateTime.now());
            order.setRealAmt(order.getTotalAmt());
            orderMapper.save(order);
        } else {
            // 普通用户，调用支付宝退款接口
            String orderId = reservation.getOrderId();
            Order order = orderMapper.selectById(orderId);
            // 调用退款接口
            payService.refundOrder(order);
        }

        return result;
    }
}
